<?php
/**
 * Created by PhpStorm.
 * User: Apache
 * Date: 2019/12/13
 * Time: 10:03
 */

namespace app\api\controller\followmanage;
use app\api\controller\common\ApiBase;
use app\api\model\Admin as AdminModel;
use Think\Db;

class Companyfollowcontract extends ApiBase
{
    protected $admin;
    protected $model = null;
    protected $statusArr = [0=>'未处理',1=>'通过',2=>'拒绝'];
    protected $backArr = [0=>'未回传',1=>'已回传'];
    public function _initialize()
    {
        parent::_initialize();
        $this->admin = session('admin');
        $this->model = model('CompanyFollowContract');
    }

    /**
     * 合同列表
     */
    public function getList(){
        $exhibition = $this->request->param('exhibition');
        if(empty($exhibition)){
            return json(['code'=>-1,'msg'=>'缺少关键主键展会id']);
        }
        $zs_name=$this->request->param('zs_name');
        $zs_name = isset($zs_name) && $zs_name != '' ? $zs_name : '';
        $status = $this->request->param('status');
        $status = isset($status) && $status != '' ? $status : -1;
        $page = $this->request->param('page');
        $page = isset($page) && $page != '' ? $page : 1;
//        $back = input('back');
//        $back = isset($back) && $back != '' ? $back : -1;
        $member_id = input('member_id');
        $member_id = isset($member_id) && $member_id != '' ? $member_id : '';
        $pageSize = input('pageSize');
        $pageSize = isset($pageSize) && $pageSize != '' ? $pageSize : 10;

        $where['h.is_delete'] = 0;
        if(!empty($exhibition)){
            $where['h.id_zhui'] = $exhibition;
        }

        if(!empty($zs_name)){
            $where['h.name_zs'] = array('like','%'.$zs_name.'%');
        }

//        if(is_numeric($back)&&$back>=0){
//            $where['h.is_back'] = $back;
//        }

        if(is_numeric($status)&&$status>=0){
            $where['h.s_status'] = $status;
        }

        if(is_numeric($member_id)&&$member_id>0){
            $where['h.create_uid'] = $member_id;
        }else{
             //当前用户权限
            $role_id = db('admin_role')->where(['admin_id'=>$this->admin['id']])->value('role_id');
            if(!$role_id && $this->admin['is_super']==0){
                return json(['code'=>0,'msg'=>'角色不存在']);
            }
            $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
            if($this->admin['is_super'] == 1){
                //不加限制条件
            }else{
                if($is_gl == 1){
                    $w['org_id_tree'] = ['like', "%".$this->admin['org_id']."%"];
                    //所有所属组织的用户 id
                    $adminarr =db('admin')->field('id')->where($w)->select();
                    $admin_ids = array_column($adminarr,'id');
                    $where['h.create_uid'] = array('in',$admin_ids);
                }else{
                    $where['h.create_uid'] = $this->admin['id'];
                }
            }
        }
        $page = max(1,intval($page));
        $list = db('contract')
                    ->alias('h')
                    ->field('h.*,e.id exhibition_id,e.title,a.realname')
                    ->join('exhibition e','h.id_zhui=e.id','left')
                    ->join('admin a','h.create_uid=a.id','left')
                    ->where($where)
                    ->order('id desc')
                    ->limit(($page-1)*$pageSize.','.$pageSize)
                    ->select();

        $total = db('contract')
                    ->alias('h')
                    ->field('h*,e.id as exhibition_id,e.name,a.realname')
                    ->join('exhibition e','h.id_zhui=e.id','left')
                    ->join('admin a','h.create_uid=a.id','left')
                    ->where($where)
                    ->count();

        if(!empty($list)){
            $ev['status']=array('gt',1);
             $ev['is_delete']=0;
            foreach ($list as &$v){
                $ev['contract_id']=$v['id'];
                $ftotal=db('finance')->field('sum(fee) as f_total')->where($ev)->select();
                $v['f_total'] =  empty($ftotal)?'0.00':$ftotal[0]['f_total'];
            }
            unset($v);
        }

        return json(['code'=>1,'msg'=>'success','data'=>['list'=>$list,'count'=>$total]]);

    }
//    /**
//     * 合同审核
//     */
//    public function signContract(){
//        $data['is_contract'] = 1;
//        $where['id'] = $this->request->param('id');
//        $where['status'] = array('<>',-1);
//
//        $r = $this->model->findWhere($where);
//        if(!$r){
//            return json(['code'=>0,'msg'=>'记录不存在']);
//        }
//
//        $r = $this->model->updateBywhere($data,$where);
//        if(!$r){
//            return json(['code'=>0,'msg'=>'操作失败，请重试']);
//        }
//
//        return json(['code'=>1,'msg'=>'操作成功']);
//    }

    /**
     * 财务审核
     */
    public function payOrder(){
        $data['is_pay'] = 1;
        $where['id'] = $this->request->param('id');
        $where['status'] = array('<>',-1);

        $r = $this->model->findWhere($where);
        if(!$r){
            return json(['code'=>0,'msg'=>'记录不存在']);
        }
        $r = $this->model->updateBywhere($data,$where);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        #添加操作记录
        $logData['follow_id'] = $r['follow_id'];
        $logData['public_id'] = db('company_follow')->where(['id'=>$r['follow_id']])->value('public_id');
        $logData['member_id'] = $r['member_id'];
        $logData['content'] = $this->admin['realname'].'操作财务审核，由'.$this->statusArr[$r['is_pay']].'变更为'.$this->statusArr[$data['is_pay']];

        setFollowLog($logData);
        return json(['code'=>1,'msg'=>'操作成功']);
    }
    
    /**
     * 删除合同
     */
    public function delete(){
        $id = input('id');
        $r = $this->model->deleteWhere(['contract_id'=>$id]);
        if(!$r){
            return json(['code'=>0,'msg'=>'操作失败，请重试']);
        }
        return json(['code'=>1,'msg'=>'操作成功']);
    }

    /**
     * 查看管理员
     *
     * @return void
     */
    public function index()
    {
        if (request()->isPost()) {
            $post = input('post.');
            $orgId = isset($post['org_id']) && $post['org_id'] != '' ? $post['org_id'] : 0;
            $pageSize = isset($post['pageSize']) && $post['pageSize'] != '' ? $post['pageSize'] : 10;
            $where['is_super'] = 0;
            if ($orgId != 0) {
                $role_id = db('admin_role')->where(['admin_id'=>$this->admin['id']])->value('role_id');
                $is_gl = db('role')->where(['id'=>$role_id])->value('is_gl');
                if($is_gl == 1){
                    $where[] = ['exp', Db::raw('FIND_IN_SET(' . $orgId . ',a.org_id_tree)')];
                }else{
                    $where['a.id']=$this->admin['id'];
                }
            }
            if (isset($post['keyword']) && $post['keyword'] != '') {
                $where['a.account|a.realname'] = ['like', '%' . $post['keyword'] . '%'];
            }
            $adminList = AdminModel::alias('a')
                ->with('role')
                ->join('crm_organization b', 'b.id = a.org_id', 'LEFT')
                ->where($where)
                ->field('a.id,a.account,a.realname,a.mobile,a.email,a.org_id,b.org_name,a.create_time,a.update_time')
                ->paginate($pageSize);
            $list = $adminList->toArray();
            unset($list['per_page'], $list['last_page']);
            return json(array('code' => '1', 'msg' => '成功', 'data' => $list));
        } else {
            return json(array('code' => '0', 'msg' => '请求失败'));
        }
    }

}